package com.doctor.ui.office;

import java.util.ArrayList;
import java.util.List;

import com.doctor.adapter.OfficeAdapter;
import com.doctor.bean.OfficeBean;
import com.doctor.comm.AlarmReceiver;
import com.doctor.comm.ConstConfig;
import com.doctor.comm.DialogHelper;
import com.doctor.comm.DialogHelper.DialogSelectCallback;
import com.doctor.comm.DialogHelper.NoticeDialogCallback;
import com.doctor.comm.FragmentHelper;
import com.doctor.database.DbOperator;
import com.doctor.ui.BaseFragment;
import com.doctor.ui.R;
import com.doctor.view.PullToRefreshListView;
import com.doctor.view.PullToRefreshListView.OnRefreshListener;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class OfficeBaseFrag extends BaseFragment{

	/**
	 * 无纸办公要事提醒各子界面的父类
	 */
	
	protected Context context;
	protected String[] operation={"修改","删除","取消"};
	protected PullToRefreshListView listView;
	protected OfficeAdapter adapter;
	protected View listFoot,listHead;
	protected TextView footMore;
	protected ProgressBar footProgress;
	protected PublishInfoFrag publishInfoFrag;
	protected ModifyInfoFrag modifyInfoFrag;
	protected LookInfoFrag lookInfoFrag;
	protected LinearLayout addBtn;    //添加按钮
	//从第1行开始查询
	protected int fromRow=0;
	protected List<OfficeBean> beanList=new ArrayList<OfficeBean>();
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		context=getActivity();
		
	}
	
	@Override
	public void onPause() {
		super.onPause();
	}
	
	//字类必须重写
	protected String getTable(){
		return "";
	}
	
	//子类必须重写
    protected void setTable(Bundle bundle, String tableName){
		
	}
	
	
	protected final void initiaView(View view){
		fromRow=0;
		addBtn=(LinearLayout) view.findViewById(R.id.addBtn);
		addBtn.setOnClickListener(new View.OnClickListener() {			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			    publishInfoFrag=null;
				publishInfoFrag=new PublishInfoFrag();
				Bundle bundle=new Bundle();
				setTable(bundle, getTable());
				//fragment间传递数据
				publishInfoFrag.setArguments(bundle);
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, publishInfoFrag).addToBackStack(null).commit();
			}
		});
		listView=(PullToRefreshListView) view.findViewById(R.id.listView);
		listFoot=View.inflate(getActivity(), R.layout.listview_footer, null);
		footMore=(TextView) listFoot.findViewById(R.id.listview_foot_more);
		footProgress=(ProgressBar) listFoot.findViewById(R.id.listview_foot_progress);
		// 添加底部视图 必须在setAdapter前
		listView.addFooterView(listFoot);
				
		adapter=new OfficeAdapter(context,beanList);
		listView.setAdapter(adapter);
		
		listView.setOnScrollListener(new OnScrollListener() {			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				listView.onScrollStateChanged(view, scrollState);		
				if (adapter.getCount()==0) {
					return;
				}
				//判断是否滚动到底部
				boolean scrollEnd=false;
				try {
					if (view.getPositionForView(listFoot)==view.getLastVisiblePosition()) {
						scrollEnd=true;
					}
				} catch (Exception e) {
					scrollEnd=false;
					e.printStackTrace();					
				}
				
				if (scrollEnd && scrollState==SCROLL_STATE_TOUCH_SCROLL) {
					//下拉刷新
					footMore.setText(R.string.loading_data);
					footProgress.setVisibility(View.VISIBLE);
					footMore.setVisibility(View.VISIBLE);
					fromRow=adapter.getCount();
					freshData(fromRow);
				}	
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub
				listView.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
			}
		});
		
		listView.setOnRefreshListener(new OnRefreshListener() {			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				//上拉刷新
				listView.onRefreshComplete();
				fromRow=0;
				freshData(fromRow);
			}
		});
		
		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				final OfficeBean bean=(OfficeBean) arg1.getTag(R.id.bean_tag);
				lookInfoFrag=null;
				lookInfoFrag=new LookInfoFrag();
				Bundle bundle=new Bundle();
				bundle.putSerializable(ConstConfig.BEAN, bean);
				bundle.putString(ConstConfig.TABLE, getTable());
				//fragment间传递数据
				lookInfoFrag.setArguments(bundle);
				FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
				FragmentHelper.setFragSwitchAnimation(transaction);
				transaction.replace(R.id.frag_container, lookInfoFrag).addToBackStack(null).commit();
			}
		});
		
		listView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				// TODO Auto-generated method stub
				if (arg1==listFoot) {
					//点击底部栏无效
					return true;
				}
				
				final OfficeBean bean=(OfficeBean) arg1.getTag(R.id.bean_tag);
				//减去header占去的一个位置才是item的真实位置
				final int beanPosition=arg2-1;
				
				DialogHelper.selectDialog(context, null, operation, new DialogSelectCallback() {
					@Override
					public void onDialogSelected(int position1) {
						// TODO Auto-generated method stub
						if (position1==0) {
							//修改
							modifyInfoFrag=null;
							modifyInfoFrag=new ModifyInfoFrag();
							Bundle bundle=new Bundle();
							setTable(bundle, getTable());
							bundle.putSerializable(ConstConfig.BEAN, bean);
							//fragment间传递数据
							modifyInfoFrag.setArguments(bundle);
							FragmentTransaction transaction=getActivity().getSupportFragmentManager().beginTransaction();
							FragmentHelper.setFragSwitchAnimation(transaction);
							transaction.replace(R.id.frag_container, modifyInfoFrag).addToBackStack(null).commit();
							
						} else if (position1==1) {
							DialogHelper.noticeDialog(context, null, new NoticeDialogCallback() {								
								@Override
								public void onClicked(int position2) {
									// TODO Auto-generated method stub
									if (position2==1) {
										//删除
										int alarmId=DbOperator.getInstance(context).getAlarmIdById(getTable(), bean.getId());
										int row=DbOperator.getInstance(context).deleteData(getTable(), bean.getId());
										String deleteResult=row>0?"成功！":"失败！";
										Toast.makeText(context, "删除"+deleteResult, Toast.LENGTH_SHORT).show();
										if (row>0) {
											//更新adapter数据
											adapter.removeBean(beanPosition);
											if (alarmId>0) {
												AlarmReceiver.cancelAlarm(getActivity(), alarmId);
											}
										}
									}
								}
							});
						}
					}
				});
				return true;
			}
		});		
		freshData(fromRow);
	}
    	
	//刷新数据
	protected final void freshData(final int fromRow){
		if (fromRow<=0) {
			adapter.clear();
			//上拉刷新后id从头开始计数
			this.fromRow=0;
			adapter.notifyDataSetChanged();
		}
		
		new Thread() {
			public void run() {
				try {
					sleep(DbOperator.delayTime);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				final List<OfficeBean> list=DbOperator.getInstance(context).selectOfficeData(getTable(), fromRow);
				getActivity().runOnUiThread(new Runnable() {
					@Override
					public void run() {
						// TODO Auto-generated method stub
						if (list!=null && list.size()>0) {
							for (OfficeBean bean : list) {
								adapter.addBean(bean);
							}
							adapter.notifyDataSetChanged();
						}
						footMore.setText(R.string.more);
						footMore.setVisibility(View.GONE);
						footProgress.setVisibility(View.GONE);
					}
				});
			}
		}.start();
	}
	
	
}
